<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>班级积分管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <!-- CryptoJS库用于密码加密 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#F59E0B',
                        danger: '#EF4444',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
            .hover-lift {
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }
            .hover-lift:hover {
                transform: translateY(-5px);
                box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            }
            .gradient-bg {
                background: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%);
            }
            .pulse-animation {
                animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            @keyframes pulse {
                0%, 100% {
                    opacity: 1;
                }
                50% {
                    opacity: 0.7;
                }
            }
            
            /* 登录页特定样式 */
            .login-container {
                background: white;
                border-radius: 16px;
                box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
                width: 100%;
                max-width: 420px;
                overflow: hidden;
            }
            
            .login-header {
                background: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%);
                padding: 30px;
                text-align: center;
                color: white;
            }
            
            .login-body {
                padding: 30px;
            }
            
            .input-icon {
                position: absolute;
                left: 15px;
                top: 50%;
                transform: translateY(-50%);
                color: #9CA3AF;
            }
            
            .btn-login {
                width: 100%;
                padding: 15px;
                background: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%);
                color: white;
                border: none;
                border-radius: 10px;
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s;
                box-shadow: 0 4px 6px rgba(59, 130, 246, 0.2);
            }
            
            .btn-login:hover {
                transform: translateY(-2px);
                box-shadow: 0 7px 14px rgba(59, 130, 246, 0.3);
            }
            
            .btn-login:active {
                transform: translateY(0);
            }
            
            .error-message {
                color: #EF4444;
                font-size: 14px;
                margin-top: 8px;
                display: none;
            }
            
            .success-message {
                color: #10B981;
                font-size: 14px;
                margin-top: 8px;
                display: none;
            }
            
            .pulse {
                animation: pulse 1.5s infinite;
            }
            
            @keyframes pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.05); }
                100% { transform: scale(1); }
            }
            
            .shake {
                animation: shake 0.5s;
            }
            
            @keyframes shake {
                0%, 100% { transform: translateX(0); }
                10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
                20%, 40%, 60%, 80% { transform: translateX(5px); }
            }
        }
    </style>
    
    <!-- 打印样式 -->
    <style media="print">
        @media print {
            /* 隐藏不需要打印的元素 */
            #login-page, #app-page header, #app-page footer, .nav-tab, 
            .action-buttons, #toast, .modal-backdrop, .modal {
                display: none !important;
            }
            
            /* 调整打印内容样式 */
            body, #app-page, #app-page main, .container {
                background: white !important;
                color: black !important;
                padding: 0 !important;
                margin: 0 !important;
                width: 100 !important;
            }
            
            .bg-white {
                box-shadow: none !important;
                border: none !important;
            }
            
            table {
                border-collapse: collapse !important;
                width: 100% !important;
            }
            
            th, td {
                border: 1px solid #ccc !important;
                padding: 8px !important;
            }
            
            th {
                background-color: #f2f2f2 !important;
            }
            
            /* 打印标题 */
            .print-title {
                text-align: center !important;
                margin: 20px 0 !important;
                font-size: 24px !important;
                font-weight: bold !important;
            }
            
            /* 打印日期 */
            .print-date {
                text-align: right !important;
                margin-bottom: 20px !important;
                font-style: italic !important;
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 text-dark min-h-screen flex flex-col">
    <!-- 登录页面 -->
    <div id="login-page" class="flex-grow flex items-center justify-center p-4">
        <div class="login-container">
            <div class="login-header">
                <i class="fa-solid fa-graduation-cap text-white text-4xl mb-3"></i>
                <h1 class="text-2xl font-bold">班级积分管理系统</h1>
                <p class="text-blue-100 mt-2">请登录以继续</p>
            </div>
            
            <div class="login-body">
                <form id="login-form">
                    <div class="mb-4">
                        <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                        <div class="relative">
                            <div class="input-icon">
                                <i class="fa-solid fa-user"></i>
                            </div>
                            <input type="text" id="username" name="username" 
                                class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                placeholder="输入用户名" autocomplete="off">
                        </div>
                        <div id="usernameError" class="error-message">
                            <i class="fa-solid fa-circle-exclamation mr-1"></i>请输入用户名
                        </div>
                    </div>
                    
                    <div class="mb-6">
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <div class="relative">
                            <div class="input-icon">
                                <i class="fa-solid fa-lock"></i>
                            </div>
                            <input type="password" id="password" name="password" 
                                class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                placeholder="输入密码">
                        </div>
                        <div id="passwordError" class="error-message">
                            <i class="fa-solid fa-circle-exclamation mr-1"></i>请输入密码
                        </div>
                    </div>
                    
                    <button type="submit" class="btn-login pulse">
                        <i class="fa-solid fa-sign-in mr-2"></i>登录
                    </button>
                    
                    <div id="loginError" class="error-message">
                        <i class="fa-solid fa-circle-exclamation mr-1"></i>用户名或密码不正确
                    </div>
                    
                    <div id="loginSuccess" class="success-message">
                        <i class="fa-solid fa-circle-check mr-1"></i>登录成功，正在跳转...
                    </div>
                </form>
                
                <div class="text-center text-sm text-gray-50 mt-4">
                    <p>默认账号: admin 密码: admin</p>
                </div>
                
                <div class="text-center text-sm text-gray-500 mt-4">
                    <p>© 2025 班级积分管理系统 | 澎博小学501班</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 主应用页面 -->
    <div id="app-page" class="hidden flex flex-col h-screen">
        <!-- 顶部导航栏 -->
        <header class="bg-white shadow-sm z-10">
            <div class="container mx-auto px-4">
                <div class="flex justify-between items-center py-4">
                    <div class="flex items-center space-x-3">
                        <i class="fa-solid fa-graduation-cap text-primary text-2xl"></i>
                        <h1 class="text-xl font-bold text-dark">班级积分管理系统</h1>
                    </div>
                    <div class="flex items-center space-x-4">
                        <div class="hidden md:flex items-center space-x-2 text-gray-600">
                            <i class="fa-solid fa-user-circle text-lg"></i>
                            <span id="current-user">管理员</span>
                        </div>
                        <button id="change-password-btn" class="text-gray-500 hover:text-primary transition-colors">
                            <i class="fa-solid fa-key text-xl"></i>
                        </button>
                        <button id="logout-btn" class="text-gray-500 hover:text-danger transition-colors">
                            <i class="fa-solid fa-sign-out text-xl"></i>
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <!-- 主要内容区 -->
        <main class="flex-grow overflow-auto">
            <div class="container mx-auto px-4 py-6">
                <!-- 导航标签 -->
                <div class="mb-6 border-b border-gray-200">
                    <nav class="-mb-px flex space-x-8 overflow-x-auto pb-2">
                        <button id="nav-students" class="nav-tab active whitespace-nowrap py-4 px-1 border-b-2 border-primary text-primary font-medium">
                            <i class="fa-solid fa-users mr-2"></i>学生管理
                        </button>
                        <button id="nav-scores" class="nav-tab whitespace-nowrap py-4 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium">
                            <i class="fa-solid fa-plus-minus mr-2"></i>积分操作
                        </button>
                        <button id="nav-ranking" class="nav-tab whitespace-nowrap py-4 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium">
                            <i class="fa-solid fa-trophy mr-2"></i>积分排行
                        </button>
                        <button id="nav-records" class="nav-tab whitespace-nowrap py-4 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium">
                            <i class="fa-solid fa-history mr-2"></i>积分记录
                        </button>
                        <!-- 积分兑换导航 -->
                        <button id="nav-rewards" class="nav-tab whitespace-nowrap py-4 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium">
                            <i class="fa-solid fa-gift mr-2"></i>积分兑换
                        </button>
                    </nav>
                </div>

                <!-- 学生管理页面 -->
                <div id="students-page" class="tab-content">
                    <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                        <h2 class="text-xl font-bold mb-4">学生管理</h2>
                        <div class="flex flex-wrap gap-4 mb-6 action-buttons">
                            <button id="import-students-btn" class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                <i class="fa-solid fa-file-import mr-2"></i>导入学生名单
                            </button>
                            <button id="add-student-btn" class="bg-secondary hover:bg-secondary/90 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                <i class="fa-solid fa-user-plus mr-2"></i>添加学生
                            </button>
                            <button id="delete-selected-btn" class="bg-danger hover:bg-danger/90 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                <i class="fa-solid fa-user-minus mr-2"></i>删除选中
                            </button>
                            <button id="add-score-selected-btn" class="bg-accent hover:bg-accent/90 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                <i class="fa-solid fa-plus mr-2"></i>多选加分
                            </button>
                            <button id="export-students-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                <i class="fa-solid fa-file-export mr-2"></i>导出学生列表
                            </button>
                            <button id="print-students-btn" class="bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                <i class="fa-solid fa-print mr-2"></i>打印学生列表
                            </button>
                            <input type="file" id="student-file-input" accept=".xlsx,.xls,.csv" class="hidden">
                        </div>
                        
                        <div class="mb-4">
                            <div class="relative">
                                <input type="text" id="student-search" placeholder="搜索学生..." 
                                    class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <i class="fa-solid fa-search text-gray-400"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-12">
                                            <input type="checkbox" id="select-all-students" class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                                        </th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">当前积分</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="students-table-body" class="bg-white divide-y divide-gray-200">
                                    <!-- 学生数据将通过JavaScript动态添加 -->
                                    <tr>
                                        <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                                            <i class="fa-solid fa-file-circle-question text-3xl mb-2 block"></i>
                                            暂无学生数据，请导入或添加学生
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- 积分操作页面 -->
                <div id="scores-page" class="tab-content hidden">
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- 左侧学生列表 -->
                        <div class="lg:col-span-1">
                            <div class="bg-white rounded-xl shadow-md p-6 h-full">
                                <h2 class="text-xl font-bold mb-4">学生列表</h2>
                                
                                <div class="mb-4">
                                    <div class="relative">
                                        <input type="text" id="score-student-search" placeholder="搜索学生..." 
                                            class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <i class="fa-solid fa-search text-gray-400"></i>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="overflow-y-auto max-h-[500px]">
                                    <ul id="score-students-list" class="space-y-2">
                                        <!-- 学生数据将通过JavaScript动态添加 -->
                                        <li class="text-center text-gray-500 py-10">
                                            <i class="fa-solid fa-file-circle-question text-3xl mb-2 block"></i>
                                            暂无学生数据
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 右侧积分操作 -->
                        <div class="lg:col-span-2">
                            <div class="bg-white rounded-xl shadow-md p-6">
                                <h2 class="text-xl font-bold mb-4">积分操作</h2>
                                
                                <div id="no-student-selected" class="py-10 text-center">
                                    <i class="fa-solid fa-hand-pointer text-3xl text-gray-400 mb-3"></i>
                                    <p class="text-gray-500">请从左侧选择一个学生</p>
                                </div>
                                
                                <div id="score-operation-form" class="hidden">
                                    <div class="mb-6 p-4 bg-blue-50 rounded-lg border border-blue-100">
                                        <h3 class="text-lg font-medium text-blue-800 flex items-center">
                                            <i class="fa-solid fa-user-circle mr-2"></i>
                                            <span id="selected-student-name">-</span>
                                            <span class="ml-2 text-sm font-normal text-gray-600">当前积分: <span id="selected-student-score">0</span></span>
                                        </h3>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <label class="block text-sm font-medium text-gray-700 mb-1">积分变动</label>
                                        <div class="flex items-center space-x-4">
                                            <div class="flex-grow">
                                                <input type="number" id="score-change" min="1" value="1" 
                                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                                            </div>
                                            <div class="flex space-x-2">
                                                <button type="button" id="btn-add-score" class="bg-secondary hover:bg-secondary/90 text-white font-medium py-2 px-6 rounded-lg transition-all shadow">
                                                    <i class="fa-solid fa-plus mr-1"></i>加分
                                                </button>
                                                <button type="button" id="btn-subtract-score" class="bg-danger hover:bg-danger/90 text-white font-medium py-2 px-6 rounded-lg transition-all shadow">
                                                    <i class="fa-solid fa-minus mr-1"></i>减分
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-6">
                                        <label for="score-reason" class="block text-sm font-medium text-gray-700 mb-1">原因</label>
                                        <textarea id="score-reason" rows="3" 
                                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                            placeholder="请输入积分变动原因"></textarea>
                                    </div>
                                    
                                    <div class="flex justify-end">
                                        <button id="reset-score-form" class="mr-3 bg-gray-200 hover:bg-gray-300 text-gray-700 font-medium py-2 px-6 rounded-lg transition-all">
                                            重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 积分排行页面 -->
                <div id="ranking-page" class="tab-content hidden">
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- 左侧排行榜 -->
                        <div class="lg:col-span-2">
                            <div class="bg-white rounded-xl shadow-md p-6">
                                <div class="flex flex-wrap justify-between items-center mb-6">
                                    <h2 class="text-xl font-bold">积分排行榜</h2>
                                    <div class="flex flex-wrap gap-2 action-buttons">
                                        <button id="export-ranking-btn" class="bg-accent hover:bg-accent/90 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                            <i class="fa-solid fa-file-export mr-2"></i>导出排行榜
                                        </button>
                                        <button id="print-ranking-btn" class="bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                            <i class="fa-solid fa-print mr-2"></i>打印排行榜
                                        </button>
                                    </div>
                                    <div class="flex space-x-2 mt-2 sm:mt-0">
                                        <button class="ranking-filter-btn active px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium" data-filter="all">
                                            全部
                                        </button>
                                        <button class="ranking-filter-btn px-4 py-2 rounded-lg bg-gray-200 text-gray-700 text-sm font-medium" data-filter="top10">
                                            前10名
                                        </button>
                                        <button class="ranking-filter-btn px-4 py-2 rounded-lg bg-gray-200 text-gray-700 text-sm font-medium" data-filter="bottom10">
                                            后10名
                                        </button>
                                    </div>
                                </div>
                                
                                <div id="ranking-list" class="space-y-3">
                                    <!-- 排行榜数据将通过JavaScript动态添加 -->
                                    <div class="text-center text-gray-500 py-10">
                                        <i class="fa-solid fa-trophy text-3xl mb-2 block text-gray-300"></i>
                                        暂无排名数据
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 右侧图表 -->
                        <div class="lg:col-span-1">
                            <div class="bg-white rounded-xl shadow-md p-6 h-full">
                                <h2 class="text-xl font-bold mb-4">积分分布</h2>
                                <div class="h-[300px]">
                                    <canvas id="score-distribution-chart"></canvas>
                                </div>
                                
                                <div class="mt-6 pt-6 border-t border-gray-200">
                                    <h3 class="text-lg font-medium mb-3">班级积分统计</h3>
                                    <div class="grid grid-cols-2 gap-4">
                                        <div class="bg-gray-50 p-3 rounded-lg">
                                            <p class="text-sm text-gray-500">总人数</p>
                                            <p id="total-students" class="text-2xl font-bold">0</p>
                                        </div>
                                        <div class="bg-gray-50 p-3 rounded-lg">
                                            <p class="text-sm text-gray-500">平均积分</p>
                                            <p id="avg-score" class="text-2xl font-bold">0</p>
                                        </div>
                                        <div class="bg-gray-50 p-3 rounded-lg">
                                            <p class="text-sm text-gray-500">最高积分</p>
                                            <p id="max-score" class="text-2xl font-bold">0</p>
                                        </div>
                                        <div class="bg-gray-50 p-3 rounded-lg">
                                            <p class="text-sm text-gray-500">最低积分</p>
                                            <p id="min-score" class="text-2xl font-bold">0</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 积分记录页面 -->
                <div id="records-page" class="tab-content hidden">
                    <div class="bg-white rounded-xl shadow-md p-6">
                        <div class="flex flex-wrap justify-between items-center mb-6">
                            <h2 class="text-xl font-bold">积分记录</h2>
                            <div class="flex flex-wrap gap-2 mt-2 sm:mt-0 action-buttons">
                                <button id="export-records-btn" class="bg-accent hover:bg-accent/90 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                    <i class="fa-solid fa-file-export mr-2"></i>导出记录
                                </button>
                                <button id="print-records-btn" class="bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                    <i class="fa-solid fa-print mr-2"></i>打印记录
                                </button>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">学生筛选</label>
                                <select id="record-student-filter" class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                                    <option value="all">所有学生</option>
                                    <!-- 学生选项将通过JavaScript动态添加 -->
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">时间范围</label>
                                <select id="record-time-filter" class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                                    <option value="all">全部时间</option>
                                    <option value="today">今天</option>
                                    <option value="week">本周</option>
                                    <option value="month">本月</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">操作类型</label>
                                <select id="record-type-filter" class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                                    <option value="all">全部操作</option>
                                    <option value="add">加分</option>
                                    <option value="subtract">减分</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">积分变动</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">原因</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作人</th>
                                    </tr>
                                </thead>
                                <tbody id="records-table-body" class="bg-white divide-y divide-gray-200">
                                    <!-- 记录数据将通过JavaScript动态添加 -->
                                    <tr>
                                        <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                                            <i class="fa-solid fa-history text-3xl mb-2 block"></i>
                                            暂无积分记录
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- 积分兑换页面 -->
                <div id="rewards-page" class="tab-content hidden">
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- 左侧礼品列表 -->
                        <div class="lg:col-span-2">
                            <div class="bg-white rounded-xl shadow-md p-6">
                                <div class="flex flex-wrap justify-between items-center mb-6">
                                    <h2 class="text-xl font-bold">礼品兑换中心</h2>
                                    <div class="flex flex-wrap gap-2 action-buttons">
                                        <button id="add-reward-btn" class="bg-secondary hover:bg-secondary/90 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                            <i class="fa-solid fa-plus mr-2"></i>添加礼品
                                        </button>
                                        <button id="export-redemptions-btn" class="bg-accent hover:bg-accent/90 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                            <i class="fa-solid fa-file-export mr-2"></i>导出兑换记录
                                        </button>
                                        <button id="print-redemptions-btn" class="bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-lg transition-all shadow flex items-center">
                                            <i class="fa-solid fa-print mr-2"></i>打印兑换记录
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="mb-6">
                                    <div class="relative">
                                        <input type="text" id="reward-search" placeholder="搜索礼品..." 
                                            class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <i class="fa-solid fa-search text-gray-400"></i>
                                        </div>
                                    </div>
                                </div>
                                
                                <div id="rewards-list" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <!-- 礼品数据将通过JavaScript动态添加 -->
                                    <div class="col-span-full text-center text-gray-500 py-10">
                                        <i class="fa-solid fa-gift text-3xl mb-2 block text-gray-300"></i>
                                        暂无礼品数据，请添加礼品
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 右侧兑换记录 -->
                        <div class="lg:col-span-1">
                            <div class="bg-white rounded-xl shadow-md p-6 h-full">
                                <h2 class="text-xl font-bold mb-4">兑换记录</h2>
                                
                                <div class="mb-4">
                                    <select id="redemption-student-filter" class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                                        <option value="all">所有学生</option>
                                        <!-- 学生选项将通过JavaScript动态添加 -->
                                    </select>
                                </div>
                                
                                <div class="overflow-y-auto max-h-[500px]">
                                    <div id="redemptions-list" class="space-y-3">
                                        <!-- 兑换记录将通过JavaScript动态添加 -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- 页脚 -->
        <footer class="bg-white border-t border-gray-200 py-4">
            <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
                <p>© 2025 班级积分管理系统 | 澎博小学501班</p>
            </div>
        </footer>
    </div>

    <!-- 添加学生模态框 -->
    <div id="add-student-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-bold">添加学生</h3>
            </div>
            <div class="p-6">
                <form id="add-student-form" class="space-y-4">
                    <div>
                        <label for="new-student-name" class="block text-sm font-medium text-gray-700 mb-1">学生姓名</label>
                        <input type="text" id="new-student-name" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请输入学生姓名">
                    </div>
                    <div>
                        <label for="new-student-score" class="block text-sm font-medium text-gray-700 mb-1">初始积分</label>
                        <input type="number" id="new-student-score" min="0" value="0"
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请输入初始积分">
                    </div>
                </form>
            </div>
            <div class="p-4 bg-gray-50 rounded-b-xl flex justify-end space-x-3">
                <button id="cancel-add-student" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button id="confirm-add-student" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                    添加
                </button>
            </div>
        </div>
    </div>

    <!-- 添加礼品模态框 -->
    <div id="add-reward-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-bold" id="reward-modal-title">添加礼品</h3>
            </div>
            <div class="p-6">
                <form id="add-reward-form" class="space-y-4">
                    <input type="hidden" id="reward-id">
                    <div>
                        <label for="reward-name" class="block text-sm font-medium text-gray-700 mb-1">礼品名称</label>
                        <input type="text" id="reward-name" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请输入礼品名称">
                    </div>
                    <div>
                        <label for="reward-points" class="block text-sm font-medium text-gray-700 mb-1">所需积分</label>
                        <input type="number" id="reward-points" min="1" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请输入所需积分">
                    </div>
                    <div>
                        <label for="reward-description" class="block text-sm font-medium text-gray-700 mb-1">礼品描述</label>
                        <textarea id="reward-description" rows="3"
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请输入礼品描述（可选）"></textarea>
                    </div>
                    <div>
                        <label for="reward-stock" class="block text-sm font-medium text-gray-700 mb-1">库存数量</label>
                        <input type="number" id="reward-stock" min="0" value="1" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请输入库存数量">
                    </div>
                </form>
            </div>
            <div class="p-4 bg-gray-50 rounded-b-xl flex justify-end space-x-3">
                <button id="cancel-add-reward" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button id="confirm-add-reward" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                    保存
                </button>
            </div>
        </div>
    </div>

    <!-- 兑换礼品模态框 -->
    <div id="redeem-reward-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-bold">兑换礼品</h3>
            </div>
            <div class="p-6">
                <input type="hidden" id="redeem-reward-id">
                <div class="mb-4 p-4 bg-blue-50 rounded-lg border border-blue-100">
                    <h4 class="font-medium text-blue-800 mb-2" id="redeem-reward-name">-</h4>
                    <p class="text-sm text-gray-600 mb-1">所需积分: <span id="redeem-reward-points" class="font-medium">0</span></p>
                    <p class="text-sm text-gray-600" id="redeem-reward-description"></p>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">选择学生</label>
                    <select id="redeem-student-id" class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all" required>
                        <option value="">-- 请选择学生 --</option>
                        <!-- 学生选项将通过JavaScript动态添加 -->
                    </select>
                </div>
                
                <div id="student-points-info" class="mb-4 p-3 bg-gray-50 rounded-lg hidden">
                    <p class="text-sm">
                        <span id="selected-redeem-student-name"></span> 当前积分: 
                        <span id="selected-redeem-student-points" class="font-medium"></span>
                    </p>
                    <p id="points-enough-message" class="text-sm mt-1 hidden"></p>
                </div>
                
                <div class="mb-4">
                    <label for="redeem-note" class="block text-sm font-medium text-gray-700 mb-1">备注（可选）</label>
                    <textarea id="redeem-note" rows="2"
                        class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                        placeholder="请输入备注信息"></textarea>
                </div>
            </div>
            <div class="p-4 bg-gray-50 rounded-b-xl flex justify-end space-x-3">
                <button id="cancel-redeem-reward" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button id="confirm-redeem-reward" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                    确认兑换
                </button>
            </div>
        </div>
    </div>

    <!-- 更改密码模态框 -->
    <div id="change-password-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-bold">更改密码</h3>
            </div>
            <div class="p-6">
                <form id="change-password-form" class="space-y-4">
                    <div>
                        <label for="current-password" class="block text-sm font-medium text-gray-700 mb-1">当前密码</label>
                        <input type="password" id="current-password" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请输入当前密码">
                    </div>
                    <div>
                        <label for="new-password" class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                        <input type="password" id="new-password" required minlength="6"
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请输入新密码（至少6位）">
                    </div>
                    <div>
                        <label for="confirm-password" class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
                        <input type="password" id="confirm-password" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                            placeholder="请再次输入新密码">
                    </div>
                    <div id="password-error" class="hidden text-sm text-danger">
                        <i class="fa-solid fa-exclamation-circle mr-1"></i>
                        <span id="password-error-message"></span>
                    </div>
                </form>
            </div>
            <div class="p-4 bg-gray-50 rounded-b-xl flex justify-end space-x-3">
                <button id="cancel-change-password" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button id="confirm-change-password" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                    确认更改
                </button>
            </div>
        </div>
    </div>

    <!-- 多选加分模态框 -->
    <div id="multi-score-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-bold">多选加分</h3>
            </div>
            <div class="p-6">
                <div id="selected-students-list" class="mb-4 max-h-40 overflow-y-auto p-3 bg-gray-50 rounded-lg">
                    <!-- 已选学生列表将通过JavaScript动态添加 -->
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">加分值</label>
                    <input type="number" id="multi-score-change" min="1" value="1" 
                        class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                </div>
                
                <div class="mb-6">
                    <label for="multi-score-reason" class="block text-sm font-medium text-gray-700 mb-1">加分原因</label>
                    <textarea id="multi-score-reason" rows="3" 
                        class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                        placeholder="请输入加分原因"></textarea>
                </div>
            </div>
            <div class="p-4 bg-gray-50 rounded-b-xl flex justify-end space-x-3">
                <button id="cancel-multi-score" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button id="confirm-multi-score" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                    确认加分
                </button>
            </div>
        </div>
    </div>

    <!-- 提示消息组件 -->
    <div id="toast" class="fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-300 z-50 flex items-center">
        <i id="toast-icon" class="mr-2 text-xl"></i>
        <span id="toast-message"></span>
    </div>

    <script>
        // 登录功能修复
        document.addEventListener('DOMContentLoaded', function() {
            const loginForm = document.getElementById('login-form');
            const usernameInput = document.getElementById('username');
            const passwordInput = document.getElementById('password');
            const usernameError = document.getElementById('usernameError');
            const passwordError = document.getElementById('passwordError');
            const loginError = document.getElementById('loginError');
            const loginSuccess = document.getElementById('loginSuccess');
            const loginBtn = document.querySelector('.btn-login');
            
            // 表单提交处理
            loginForm.addEventListener('submit', function(e) {
                e.preventDefault(); // 阻止表单默认提交行为
                
                // 重置错误信息
                usernameError.style.display = 'none';
                passwordError.style.display = 'none';
                loginError.style.display = 'none';
                loginSuccess.style.display = 'none';
                
                // 获取输入值
                const username = usernameInput.value.trim();
                const password = passwordInput.value.trim();
                
                let isValid = true;
                
                // 验证用户名
                if (!username) {
                    usernameError.style.display = 'block';
                    isValid = false;
                }
                
                // 验证密码
                if (!password) {
                    passwordError.style.display = 'block';
                    isValid = false;
                }
                
                if (!isValid) {
                    return;
                }
                
                // 模拟登录验证
                simulateLogin(username, password);
            });
            
            // 输入时隐藏错误信息
            usernameInput.addEventListener('input', function() {
                usernameError.style.display = 'none';
                loginError.style.display = 'none';
            });
            
            passwordInput.addEventListener('input', function() {
                passwordError.style.display = 'none';
                loginError.style.display = 'none';
            });
            
            // 模拟登录函数
            function simulateLogin(username, password) {
                // 显示加载状态
                loginBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i>登录中...';
                loginBtn.disabled = true;
                
                // 模拟网络请求延迟
                setTimeout(function() {
                    // 默认账号验证
                    if (username === 'admin' && password === 'admin') {
                        // 登录成功
                        loginSuccess.style.display = 'block';
                        
                        // 更新按钮状态
                        loginBtn.innerHTML = '<i class="fa-solid fa-check mr-2"></i>登录成功';
                        loginBtn.style.background = 'linear-gradient(135deg, #10B981 0%, #059669 100%)';
                        
                        // 模拟跳转
                        setTimeout(function() {
                            document.getElementById('login-page').classList.add('hidden');
                            document.getElementById('app-page').classList.remove('hidden');
                            // 初始化主应用
                            initApp();
                        }, 1500);
                    } else {
                        // 登录失败
                        loginError.style.display = 'block';
                        
                        // 恢复按钮状态
                        loginBtn.innerHTML = '<i class="fa-solid fa-sign-in mr-2"></i>登录';
                        loginBtn.disabled = false;
                        
                        // 抖动效果提示错误
                        loginForm.classList.add('shake');
                        setTimeout(function() {
                            loginForm.classList.remove('shake');
                        }, 500);
                    }
                }, 1500);
            }
        });

        // 数据存储
        const DataStore = {
            // 初始化数据
            init() {
                if (!localStorage.getItem('users')) {
                    // 默认管理员用户，密码admin
                    const adminHash = this.hashPassword('admin');
                    localStorage.setItem('users', JSON.stringify([
                        { id: 1, username: 'admin', password: adminHash }
                    ]));
                }
                
                if (!localStorage.getItem('students')) {
                    localStorage.setItem('students', JSON.stringify([]));
                }
                
                if (!localStorage.getItem('records')) {
                    localStorage.setItem('records', JSON.stringify([]));
                }
                
                // 初始化礼品数据
                if (!localStorage.getItem('rewards')) {
                    localStorage.setItem('rewards', JSON.stringify([]));
                }
                
                // 初始化兑换记录
                if (!localStorage.getItem('redemptions')) {
                    localStorage.setItem('redemptions', JSON.stringify([]));
                }
            },
            
            // 密码加密
            hashPassword(password) {
                return CryptoJS.SHA256(password).toString();
            },
            
            // 用户相关
            getUsers() {
                return JSON.parse(localStorage.getItem('users') || '[]');
            },
            
            saveUsers(users) {
                localStorage.setItem('users', JSON.stringify(users));
            },
            
            validateUser(username, password) {
                const users = this.getUsers();
                const hash = this.hashPassword(password);
                return users.find(user => user.username === username && user.password === hash);
            },
            
            // 更新用户密码
            updateUserPassword(userId, newPassword) {
                const users = this.getUsers();
                const index = users.findIndex(user => user.id === userId);
                
                if (index !== -1) {
                    users[index].password = this.hashPassword(newPassword);
                    this.saveUsers(users);
                    return true;
                }
                return false;
            },
            
            // 学生相关
            getStudents() {
                return JSON.parse(localStorage.getItem('students') || '[]');
            },
            
            saveStudents(students) {
                localStorage.setItem('students', JSON.stringify(students));
            },
            
            addStudent(student) {
                const students = this.getStudents();
                const newId = students.length > 0 ? Math.max(...students.map(s => s.id)) + 1 : 1;
                const newStudent = { id: newId, ...student, score: student.score || 0 };
                students.push(newStudent);
                this.saveStudents(students);
                return newStudent;
            },
            
            updateStudent(updatedStudent) {
                const students = this.getStudents();
                const index = students.findIndex(s => s.id === updatedStudent.id);
                if (index !== -1) {
                    students[index] = { ...students[index], ...updatedStudent };
                    this.saveStudents(students);
                    return true;
                }
                return false;
            },
            
            deleteStudents(ids) {
                let students = this.getStudents();
                students = students.filter(s => !ids.includes(s.id));
                this.saveStudents(students);
                
                // 同时删除相关记录
                let records = this.getRecords();
                records = records.filter(r => !ids.includes(r.studentId));
                this.saveRecords(records);
                
                // 同时删除相关兑换记录
                let redemptions = this.getRedemptions();
                redemptions = redemptions.filter(r => !ids.includes(r.studentId));
                this.saveRedemptions(redemptions);
                
                return true;
            },
            
            // 记录相关
            getRecords() {
                return JSON.parse(localStorage.getItem('records') || '[]');
            },
            
            saveRecords(records) {
                localStorage.setItem('records', JSON.stringify(records));
            },
            
            addRecord(record) {
                const records = this.getRecords();
                const newId = records.length > 0 ? Math.max(...records.map(r => r.id)) + 1 : 1;
                const newRecord = { id: newId, ...record, time: new Date().toISOString() };
                records.push(newRecord);
                this.saveRecords(records);
                return newRecord;
            },
            
            // 获取学生的积分记录
            getStudentRecords(studentId) {
                return this.getRecords().filter(r => r.studentId === studentId);
            },
            
            // 礼品相关
            getRewards() {
                return JSON.parse(localStorage.getItem('rewards') || '[]');
            },
            
            saveRewards(rewards) {
                localStorage.setItem('rewards', JSON.stringify(rewards));
            },
            
            addReward(reward) {
                const rewards = this.getRewards();
                const newId = rewards.length > 0 ? Math.max(...rewards.map(r => r.id)) + 1 : 1;
                const newReward = { 
                    id: newId, 
                    ...reward,
                    stock: reward.stock || 0,
                    createdAt: new Date().toISOString()
                };
                rewards.push(newReward);
                this.saveRewards(rewards);
                return newReward;
            },
            
            updateReward(updatedReward) {
                const rewards = this.getRewards();
                const index = rewards.findIndex(r => r.id === updatedReward.id);
                if (index !== -1) {
                    rewards[index] = { ...rewards[index], ...updatedReward };
                    this.saveRewards(rewards);
                    return true;
                }
                return false;
            },
            
            deleteReward(id) {
                let rewards = this.getRewards();
                rewards = rewards.filter(r => r.id !== id);
                this.saveRewards(rewards);
                return true;
            },
            
            // 减少礼品库存
            decreaseRewardStock(id, quantity = 1) {
                const rewards = this.getRewards();
                const index = rewards.findIndex(r => r.id === id);
                if (index !== -1 && rewards[index].stock >= quantity) {
                    rewards[index].stock -= quantity;
                    this.saveRewards(rewards);
                    return true;
                }
                return false;
            },
            
            // 兑换记录相关
            getRedemptions() {
                return JSON.parse(localStorage.getItem('redemptions') || '[]');
            },
            
            saveRedemptions(redemptions) {
                localStorage.setItem('redemptions', JSON.stringify(redemptions));
            },
            
            addRedemption(redemption) {
                const redemptions = this.getRedemptions();
                const newId = redemptions.length > 0 ? Math.max(...redemptions.map(r => r.id)) + 1 : 1;
                const newRedemption = { 
                    id: newId, 
                    ...redemption,
                    time: new Date().toISOString()
                };
                redemptions.push(newRedemption);
                this.saveRedemptions(redemptions);
                return newRedemption;
            },
            
            // 获取学生的兑换记录
            getStudentRedemptions(studentId) {
                return this.getRedemptions().filter(r => r.studentId === studentId);
            }
        };

        // 应用主类
        class ScoreManagementApp {
            constructor() {
                // 初始化数据存储
                DataStore.init();
                
                // 当前登录用户
                this.currentUser = null;
                
                // 绑定DOM元素
                this.bindElements();
                
                // 绑定事件处理程序
                this.bindEvents();
                
                // 初始化图表
                this.initChart();
                
                // 初始化数据
                this.renderStudentsTable();
                this.renderScoreStudentsList();
                this.renderRankingList('all');
                this.populateStudentFilter();
                this.renderRecordsTable();
                this.renderRewardsList();
                this.populateRedemptionStudentFilter();
                this.renderRedemptionsList();
                this.populateRedeemStudentFilter();
            }
            
            // 绑定DOM元素
            bindElements() {
                // 登录页面元素
                this.loginPage = document.getElementById('login-page');
                this.appPage = document.getElementById('app-page');
                this.loginForm = document.getElementById('login-form');
                this.usernameInput = document.getElementById('username');
                this.passwordInput = document.getElementById('password');
                this.currentUserEl = document.getElementById('current-user');
                this.logoutBtn = document.getElementById('logout-btn');
                
                // 更改密码相关元素
                this.changePasswordBtn = document.getElementById('change-password-btn');
                this.changePasswordModal = document.getElementById('change-password-modal');
                this.currentPasswordInput = document.getElementById('current-password');
                this.newPasswordInput = document.getElementById('new-password');
                this.confirmPasswordInput = document.getElementById('confirm-password');
                this.cancelChangePassword = document.getElementById('cancel-change-password');
                this.confirmChangePassword = document.getElementById('confirm-change-password');
                this.passwordError = document.getElementById('password-error');
                this.passwordErrorMessage = document.getElementById('password-error-message');
                
                // 导航元素
                this.navTabs = document.querySelectorAll('.nav-tab');
                this.tabContents = document.querySelectorAll('.tab-content');
                this.navStudents = document.getElementById('nav-students');
                this.navScores = document.getElementById('nav-scores');
                this.navRanking = document.getElementById('nav-ranking');
                this.navRecords = document.getElementById('nav-records');
                this.navRewards = document.getElementById('nav-rewards'); // 积分兑换导航
                
                // 学生管理页面元素
                this.studentsPage = document.getElementById('students-page');
                this.importStudentsBtn = document.getElementById('import-students-btn');
                this.studentFileInput = document.getElementById('student-file-input');
                this.addStudentBtn = document.getElementById('add-student-btn');
                this.deleteSelectedBtn = document.getElementById('delete-selected-btn');
                this.addScoreSelectedBtn = document.getElementById('add-score-selected-btn'); // 多选加分按钮
                this.studentSearch = document.getElementById('student-search');
                this.studentsTableBody = document.getElementById('students-table-body');
                this.selectAllStudents = document.getElementById('select-all-students');
                this.exportStudentsBtn = document.getElementById('export-students-btn');
                this.printStudentsBtn = document.getElementById('print-students-btn');
                
                // 积分操作页面元素
                this.scoresPage = document.getElementById('scores-page');
                this.scoreStudentSearch = document.getElementById('score-student-search');
                this.scoreStudentsList = document.getElementById('score-students-list');
                this.noStudentSelected = document.getElementById('no-student-selected');
                this.scoreOperationForm = document.getElementById('score-operation-form');
                this.selectedStudentName = document.getElementById('selected-student-name');
                this.selectedStudentScore = document.getElementById('selected-student-score');
                this.scoreChange = document.getElementById('score-change');
                this.btnAddScore = document.getElementById('btn-add-score');
                this.btnSubtractScore = document.getElementById('btn-subtract-score');
                this.scoreReason = document.getElementById('score-reason');
                this.resetScoreForm = document.getElementById('reset-score-form');
                
                // 积分排行页面元素
                this.rankingPage = document.getElementById('ranking-page');
                this.rankingFilterBtns = document.querySelectorAll('.ranking-filter-btn');
                this.rankingList = document.getElementById('ranking-list');
                this.totalStudentsEl = document.getElementById('total-students');
                this.avgScoreEl = document.getElementById('avg-score');
                this.maxScoreEl = document.getElementById('max-score');
                this.minScoreEl = document.getElementById('min-score');
                this.exportRankingBtn = document.getElementById('export-ranking-btn');
                this.printRankingBtn = document.getElementById('print-ranking-btn');
                
                // 积分记录页面元素
                this.recordsPage = document.getElementById('records-page');
                this.recordStudentFilter = document.getElementById('record-student-filter');
                this.recordTimeFilter = document.getElementById('record-time-filter');
                this.recordTypeFilter = document.getElementById('record-type-filter');
                this.recordsTableBody = document.getElementById('records-table-body');
                this.exportRecordsBtn = document.getElementById('export-records-btn');
                this.printRecordsBtn = document.getElementById('print-records-btn');
                
                // 积分兑换页面元素
                this.rewardsPage = document.getElementById('rewards-page');
                this.rewardSearch = document.getElementById('reward-search');
                this.rewardsList = document.getElementById('rewards-list');
                this.addRewardBtn = document.getElementById('add-reward-btn');
                this.redemptionStudentFilter = document.getElementById('redemption-student-filter');
                this.redemptionsList = document.getElementById('redemptions-list');
                this.exportRedemptionsBtn = document.getElementById('export-redemptions-btn');
                this.printRedemptionsBtn = document.getElementById('print-redemptions-btn');
                
                // 添加学生模态框元素
                this.addStudentModal = document.getElementById('add-student-modal');
                this.addStudentForm = document.getElementById('add-student-form');
                this.newStudentName = document.getElementById('new-student-name');
                this.newStudentScore = document.getElementById('new-student-score');
                this.cancelAddStudent = document.getElementById('cancel-add-student');
                this.confirmAddStudent = document.getElementById('confirm-add-student');
                
                // 添加礼品模态框元素
                this.addRewardModal = document.getElementById('add-reward-modal');
                this.rewardModalTitle = document.getElementById('reward-modal-title');
                this.addRewardForm = document.getElementById('add-reward-form');
                this.rewardId = document.getElementById('reward-id');
                this.rewardName = document.getElementById('reward-name');
                this.rewardPoints = document.getElementById('reward-points');
                this.rewardDescription = document.getElementById('reward-description');
                this.rewardStock = document.getElementById('reward-stock');
                this.cancelAddReward = document.getElementById('cancel-add-reward');
                this.confirmAddReward = document.getElementById('confirm-add-reward');
                
                // 兑换礼品模态框元素
                this.redeemRewardModal = document.getElementById('redeem-reward-modal');
                this.redeemRewardId = document.getElementById('redeem-reward-id');
                this.redeemRewardName = document.getElementById('redeem-reward-name');
                this.redeemRewardPoints = document.getElementById('redeem-reward-points');
                this.redeemRewardDescription = document.getElementById('redeem-reward-description');
                this.redeemStudentId = document.getElementById('redeem-student-id');
                this.studentPointsInfo = document.getElementById('student-points-info');
                this.selectedRedeemStudentName = document.getElementById('selected-redeem-student-name');
                this.selectedRedeemStudentPoints = document.getElementById('selected-redeem-student-points');
                this.pointsEnoughMessage = document.getElementById('points-enough-message');
                this.redeemNote = document.getElementById('redeem-note');
                this.cancelRedeemReward = document.getElementById('cancel-redeem-reward');
                this.confirmRedeemReward = document.getElementById('confirm-redeem-reward');
                
                // 多选加分模态框元素
                this.multiScoreModal = document.getElementById('multi-score-modal');
                this.selectedStudentsList = document.getElementById('selected-students-list');
                this.multiScoreChange = document.getElementById('multi-score-change');
                this.multiScoreReason = document.getElementById('multi-score-reason');
                this.cancelMultiScore = document.getElementById('cancel-multi-score');
                this.confirmMultiScore = document.getElementById('confirm-multi-score');
                
                // 提示消息元素
                this.toast = document.getElementById('toast');
                this.toastIcon = document.getElementById('toast-icon');
                this.toastMessage = document.getElementById('toast-message');
                
                // 当前选中的学生
                this.selectedStudent = null;
            }
            
            // 绑定事件处理程序
            bindEvents() {
                // 退出登录
                this.logoutBtn.addEventListener('click', () => {
                    this.handleLogout();
                });
                
                // 更改密码相关事件
                this.changePasswordBtn.addEventListener('click', () => {
                    this.showChangePasswordModal();
                });
                
                this.cancelChangePassword.addEventListener('click', () => {
                    this.hideChangePasswordModal();
                });
                
                this.confirmChangePassword.addEventListener('click', () => {
                    this.handleChangePassword();
                });
                
                // 实时验证密码
                this.newPasswordInput.addEventListener('input', () => {
                    this.validatePasswordForm();
                });
                
                this.confirmPasswordInput.addEventListener('input', () => {
                    this.validatePasswordForm();
                });
                
                // 导航标签切换
                this.navTabs.forEach(tab => {
                    tab.addEventListener('click', () => {
                        this.switchTab(tab.id.replace('nav-', ''));
                    });
                });
                
                // 学生管理页面事件
                this.importStudentsBtn.addEventListener('click', () => {
                    this.studentFileInput.click();
                });
                
                this.studentFileInput.addEventListener('change', (e) => {
                    this.handleFileImport(e);
                });
                
                this.addStudentBtn.addEventListener('click', () => {
                    this.showAddStudentModal();
                });
                
                this.deleteSelectedBtn.addEventListener('click', () => {
                    this.deleteSelectedStudents();
                });
                
                // 多选加分按钮事件
                this.addScoreSelectedBtn.addEventListener('click', () => {
                    this.showMultiScoreModal();
                });
                
                this.studentSearch.addEventListener('input', () => {
                    this.renderStudentsTable();
                });
                
                this.selectAllStudents.addEventListener('change', (e) => {
                    const checkboxes = document.querySelectorAll('.student-checkbox');
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = e.target.checked;
                    });
                });
                
                this.exportStudentsBtn.addEventListener('click', () => {
                    this.exportStudents();
                });
                
                this.printStudentsBtn.addEventListener('click', () => {
                    this.printStudents();
                });
                
                // 积分操作页面事件
                this.scoreStudentSearch.addEventListener('input', () => {
                    this.renderScoreStudentsList();
                });
                
                this.btnAddScore.addEventListener('click', () => {
                    this.changeStudentScore(1);
                });
                
                this.btnSubtractScore.addEventListener('click', () => {
                    this.changeStudentScore(-1);
                });
                
                this.resetScoreForm.addEventListener('click', () => {
                    this.resetScoreOperationForm();
                });
                
                // 积分排行页面事件
                this.rankingFilterBtns.forEach(btn => {
                    btn.addEventListener('click', () => {
                        this.rankingFilterBtns.forEach(b => {
                            b.classList.remove('active', 'bg-primary', 'text-white');
                            b.classList.add('bg-gray-200', 'text-gray-700');
                        });
                        btn.classList.add('active', 'bg-primary', 'text-white');
                        btn.classList.remove('bg-gray-200', 'text-gray-700');
                        this.renderRankingList(btn.dataset.filter);
                    });
                });
                
                this.exportRankingBtn.addEventListener('click', () => {
                    const activeFilter = document.querySelector('.ranking-filter-btn.active').dataset.filter;
                    this.exportRanking(activeFilter);
                });
                
                this.printRankingBtn.addEventListener('click', () => {
                    const activeFilter = document.querySelector('.ranking-filter-btn.active').dataset.filter;
                    this.printRanking(activeFilter);
                });
                
                // 积分记录页面事件
                this.recordStudentFilter.addEventListener('change', () => {
                    this.renderRecordsTable();
                });
                
                this.recordTimeFilter.addEventListener('change', () => {
                    this.renderRecordsTable();
                });
                
                this.recordTypeFilter.addEventListener('change', () => {
                    this.renderRecordsTable();
                });
                
                this.exportRecordsBtn.addEventListener('click', () => {
                    this.exportRecords();
                });
                
                this.printRecordsBtn.addEventListener('click', () => {
                    this.printRecords();
                });
                
                // 添加学生模态框事件
                this.cancelAddStudent.addEventListener('click', () => {
                    this.hideAddStudentModal();
                });
                
                this.confirmAddStudent.addEventListener('click', () => {
                    this.handleAddStudent();
                });
                
                // 积分兑换页面事件
                this.addRewardBtn.addEventListener('click', () => {
                    this.showAddRewardModal();
                });
                
                this.rewardSearch.addEventListener('input', () => {
                    this.renderRewardsList();
                });
                
                this.redemptionStudentFilter.addEventListener('change', () => {
                    this.renderRedemptionsList();
                });
                
                this.exportRedemptionsBtn.addEventListener('click', () => {
                    this.exportRedemptions();
                });
                
                this.printRedemptionsBtn.addEventListener('click', () => {
                    this.printRedemptions();
                });
                
                // 添加礼品模态框事件
                this.cancelAddReward.addEventListener('click', () => {
                    this.hideAddRewardModal();
                });
                
                this.confirmAddReward.addEventListener('click', () => {
                    this.handleAddReward();
                });
                
                // 兑换礼品模态框事件
                this.cancelRedeemReward.addEventListener('click', () => {
                    this.hideRedeemRewardModal();
                });
                
                this.confirmRedeemReward.addEventListener('click', () => {
                    this.handleRedeemReward();
                });
                
                // 监听学生选择变化，显示积分信息
                this.redeemStudentId.addEventListener('change', () => {
                    this.updateStudentPointsInfo();
                });
                
                // 多选加分模态框事件
                this.cancelMultiScore.addEventListener('click', () => {
                    this.hideMultiScoreModal();
                });
                
                this.confirmMultiScore.addEventListener('click', () => {
                    this.handleMultiScore();
                });
            }
            
            // 初始化图表
            initChart() {
                const ctx = document.getElementById('score-distribution-chart').getContext('2d');
                this.scoreChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: [],
                        datasets: [{
                            label: '学生数量',
                            data: [],
                            backgroundColor: 'rgba(59, 130, 246, 0.7)',
                            borderColor: 'rgba(59, 130, 246, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    precision: 0
                                }
                            }
                        },
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }
            
            // 更新图表数据
            updateChart() {
                const students = DataStore.getStudents();
                if (students.length === 0) {
                    return;
                }
                
                // 计算积分分布
                const scoreRanges = [
                    '0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '81-90', '91+'
                ];
                const scoreCounts = new Array(scoreRanges.length).fill(0);
                
                students.forEach(student => {
                    const score = student.score;
                    let index = Math.floor(score / 10);
                    if (index >= scoreRanges.length) index = scoreRanges.length - 1;
                    scoreCounts[index]++;
                });
                
                // 更新图表
                this.scoreChart.data.labels = scoreRanges;
                this.scoreChart.data.datasets[0].data = scoreCounts;
                this.scoreChart.update();
                
                // 更新统计信息
                const totalStudents = students.length;
                const totalScore = students.reduce((sum, student) => sum + student.score, 0);
                const avgScore = totalStudents > 0 ? (totalScore / totalStudents).toFixed(1) : 0;
                const maxScore = Math.max(...students.map(s => s.score), 0);
                const minScore = Math.min(...students.map(s => s.score), 0);
                
                this.totalStudentsEl.textContent = totalStudents;
                this.avgScoreEl.textContent = avgScore;
                this.maxScoreEl.textContent = maxScore;
                this.minScoreEl.textContent = minScore;
            }
            
            // 切换标签页
            switchTab(tabName) {
                // 隐藏所有标签内容
                this.tabContents.forEach(tab => {
                    tab.classList.add('hidden');
                });
                
                // 移除所有标签的活动状态
                this.navTabs.forEach(tab => {
                    tab.classList.remove('active', 'border-primary', 'text-primary');
                    tab.classList.add('border-transparent', 'text-gray-500');
                });
                
                // 显示选中的标签内容
                document.getElementById(`${tabName}-page`).classList.remove('hidden');
                
                // 设置选中的标签为活动状态
                document.getElementById(`nav-${tabName}`).classList.add('active', 'border-primary', 'text-primary');
                document.getElementById(`nav-${tabName}`).classList.remove('border-transparent', 'text-gray-500');
                
                // 如果是排行页面，更新图表
                if (tabName === 'ranking') {
                    this.updateChart();
                }
            }
            
            // 显示提示消息
            showToast(message, type = 'success') {
                const toast = this.toast;
                const icon = this.toastIcon;
                const messageEl = this.toastMessage;
                
                // 设置消息和图标
                messageEl.textContent = message;
                
                if (type === 'success') {
                    toast.classList.add('bg-green-500', 'text-white');
                    toast.classList.remove('bg-red-500', 'bg-yellow-500');
                    icon.className = 'fa-solid fa-check-circle';
                } else if (type === 'error') {
                    toast.classList.add('bg-red-500', 'text-white');
                    toast.classList.remove('bg-green-500', 'bg-yellow-500');
                    icon.className = 'fa-solid fa-exclamation-circle';
                } else if (type === 'warning') {
                    toast.classList.add('bg-yellow-500', 'text-white');
                    toast.classList.remove('bg-green-500', 'bg-red-500');
                    icon.className = 'fa-solid fa-exclamation-triangle';
                }
                
                // 显示消息
                toast.classList.remove('translate-x-full');
                
                // 3秒后隐藏消息
                setTimeout(() => {
                    toast.classList.add('translate-x-full');
                }, 3000);
            }
            
            // 渲染学生表格
            renderStudentsTable() {
                const students = DataStore.getStudents();
                const searchTerm = this.studentSearch.value.toLowerCase();
                
                // 过滤学生
                const filteredStudents = students.filter(student => 
                    student.name.toLowerCase().includes(searchTerm)
                );
                
                const tbody = this.studentsTableBody;
                tbody.innerHTML = '';
                
                if (filteredStudents.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                                <i class="fa-solid fa-file-circle-question text-3xl mb-2 block"></i>
                                ${students.length === 0 ? '暂无学生数据，请导入或添加学生' : '没有找到匹配的学生'}
                            </td>
                        </tr>
                    `;
                    return;
                }
                
                // 渲染学生表格
                filteredStudents.forEach(student => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <input type="checkbox" class="student-checkbox h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded" data-id="${student.id}">
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">${student.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${student.name}</td>
                        <td class="px-6 py-4 whitespace-nowrap font-medium ${student.score >= 0 ? 'text-green-600' : 'text-red-600'}">${student.score}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 mr-3 edit-student" data-id="${student.id}">
                                <i class="fa-solid fa-pen"></i>
                            </button>
                            <button class="text-danger hover:text-danger/80 delete-student" data-id="${student.id}">
                                <i class="fa-solid fa-trash"></i>
                            </button>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
                
                // 绑定编辑和删除按钮事件
                tbody.querySelectorAll('.edit-student').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const studentId = parseInt(e.currentTarget.dataset.id);
                        this.editStudent(studentId);
                    });
                });
                
                tbody.querySelectorAll('.delete-student').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const studentId = parseInt(e.currentTarget.dataset.id);
                        this.deleteStudent(studentId);
                    });
                });
                
                // 绑定复选框事件
                tbody.querySelectorAll('.student-checkbox').forEach(checkbox => {
                    checkbox.addEventListener('change', () => {
                        this.updateSelectAllCheckbox();
                    });
                });
            }
            
            // 渲染积分操作学生列表
            renderScoreStudentsList() {
                const students = DataStore.getStudents();
                const searchTerm = this.scoreStudentSearch.value.toLowerCase();
                
                // 过滤学生
                const filteredStudents = students.filter(student => 
                    student.name.toLowerCase().includes(searchTerm)
                );
                
                const list = this.scoreStudentsList;
                list.innerHTML = '';
                
                if (filteredStudents.length === 0) {
                    list.innerHTML = `
                        <li class="text-center text-gray-500 py-10">
                            <i class="fa-solid fa-file-circle-question text-3xl mb-2 block"></i>
                            ${students.length === 0 ? '暂无学生数据' : '没有找到匹配的学生'}
                        </li>
                    `;
                    return;
                }
                
                // 渲染学生列表
                filteredStudents.forEach(student => {
                    const item = document.createElement('li');
                    item.innerHTML = `
                        <button class="w-full text-left p-3 rounded-lg border border-gray-200 hover:border-primary hover:bg-blue-50 transition-all student-item" data-id="${student.id}">
                            <div class="flex justify-between items-center">
                                <span class="font-medium">${student.name}</span>
                                <span class="font-bold ${student.score >= 0 ? 'text-green-600' : 'text-red-600'}">${student.score}分</span>
                            </div>
                        </button>
                    `;
                    list.appendChild(item);
                });
                
                // 绑定学生选择事件
                list.querySelectorAll('.student-item').forEach(item => {
                    item.addEventListener('click', (e) => {
                        const studentId = parseInt(e.currentTarget.dataset.id);
                        this.selectStudentForScoreOperation(studentId);
                    });
                });
            }
            
            // 选择学生进行积分操作
            selectStudentForScoreOperation(studentId) {
                const students = DataStore.getStudents();
                this.selectedStudent = students.find(s => s.id === studentId);
                
                if (this.selectedStudent) {
                    this.noStudentSelected.classList.add('hidden');
                    this.scoreOperationForm.classList.remove('hidden');
                    
                    this.selectedStudentName.textContent = this.selectedStudent.name;
                    this.selectedStudentScore.textContent = this.selectedStudent.score;
                }
            }
            
            // 更改学生积分
            changeStudentScore(multiplier) {
                if (!this.selectedStudent) {
                    this.showToast('请先选择一个学生', 'error');
                    return;
                }
                
                const changeValue = parseInt(this.scoreChange.value) * multiplier;
                const reason = this.scoreReason.value.trim();
                
                if (isNaN(changeValue) || changeValue === 0) {
                    this.showToast('请输入有效的积分值', 'error');
                    return;
                }
                
                if (!reason) {
                    this.showToast('请输入积分变动原因', 'error');
                    return;
                }
                
                // 更新学生积分
                const newScore = this.selectedStudent.score + changeValue;
                DataStore.updateStudent({
                    id: this.selectedStudent.id,
                    score: newScore
                });
                
                // 添加积分记录
                DataStore.addRecord({
                    studentId: this.selectedStudent.id,
                    studentName: this.selectedStudent.name,
                    change: changeValue,
                    reason: reason,
                    operator: this.currentUserEl.textContent
                });
                
                // 更新显示
                this.selectedStudentScore.textContent = newScore;
                this.selectedStudent.score = newScore;
                
                // 重置表单
                this.scoreChange.value = 1;
                this.scoreReason.value = '';
                
                this.showToast(`成功${multiplier > 0 ? '增加' : '减少'}${Math.abs(changeValue)}分`, 'success');
                
                // 更新其他页面
                this.renderStudentsTable();
                this.renderScoreStudentsList();
                this.renderRankingList('all');
                this.updateChart();
            }
            
            // 重置积分操作表单
            resetScoreOperationForm() {
                this.scoreChange.value = 1;
                this.scoreReason.value = '';
            }
            
            // 渲染排行榜
            renderRankingList(filter) {
                let students = DataStore.getStudents();
                
                // 按积分排序
                students.sort((a, b) => b.score - a.score);
                
                // 应用筛选
                if (filter === 'top10') {
                    students = students.slice(0, 10);
                } else if (filter === 'bottom10') {
                    students = students.slice(-10).reverse();
                }
                
                const rankingList = this.rankingList;
                rankingList.innerHTML = '';
                
                if (students.length === 0) {
                    rankingList.innerHTML = `
                        <div class="text-center text-gray-500 py-10">
                            <i class="fa-solid fa-trophy text-3xl mb-2 block text-gray-300"></i>
                            暂无排名数据
                        </div>
                    `;
                    return;
                }
                
                // 渲染排行榜
                students.forEach((student, index) => {
                    let rankClass = '';
                    let medalIcon = '';
                    
                    if (index === 0) {
                        rankClass = 'bg-yellow-100 border-yellow-200';
                        medalIcon = '<i class="fa-solid fa-crown text-yellow-500 mr-2"></i>';
                    } else if (index === 1) {
                        rankClass = 'bg-gray-100 border-gray-200';
                        medalIcon = '<i class="fa-solid fa-medal text-gray-500 mr-2"></i>';
                    } else if (index === 2) {
                        rankClass = 'bg-amber-100 border-amber-200';
                        medalIcon = '<i class="fa-solid fa-medal text-amber-700 mr-2"></i>';
                    } else {
                        rankClass = 'bg-white border-gray-200';
                    }
                    
                    const item = document.createElement('div');
                    item.classList.add('p-4', 'rounded-lg', 'border', 'flex', 'items-center', 'justify-between', ...rankClass.split(' '));
                    item.innerHTML = `
                        <div class="flex items-center">
                            <span class="font-bold text-lg w-8 text-center">${index + 1}</span>
                            ${medalIcon}
                            <span class="font-medium">${student.name}</span>
                        </div>
                        <span class="font-bold ${student.score >= 0 ? 'text-green-600' : 'text-red-600'}">${student.score}分</span>
                    `;
                    rankingList.appendChild(item);
                });
            }
            
            // 填充学生筛选下拉框
            populateStudentFilter() {
                const students = DataStore.getStudents();
                const filter = this.recordStudentFilter;
                
                // 清空现有选项（保留"所有学生"选项）
                while (filter.children.length > 1) {
                    filter.removeChild(filter.lastChild);
                }
                
                // 添加学生选项
                students.forEach(student => {
                    const option = document.createElement('option');
                    option.value = student.id;
                    option.textContent = student.name;
                    filter.appendChild(option);
                });
                
                // 同时填充兑换页面的学生筛选
                this.populateRedemptionStudentFilter();
                this.populateRedeemStudentFilter();
            }
            
            // 填充兑换记录学生筛选下拉框
            populateRedemptionStudentFilter() {
                const students = DataStore.getStudents();
                const filter = this.redemptionStudentFilter;
                
                // 清空现有选项（保留"所有学生"选项）
                while (filter.children.length > 1) {
                    filter.removeChild(filter.lastChild);
                }
                
                // 添加学生选项
                students.forEach(student => {
                    const option = document.createElement('option');
                    option.value = student.id;
                    option.textContent = student.name;
                    filter.appendChild(option);
                });
            }
            
            // 填充兑换模态框学生下拉框
            populateRedeemStudentFilter() {
                const students = DataStore.getStudents();
                const filter = this.redeemStudentId;
                
                // 清空现有选项（保留"-- 请选择学生 --"选项）
                filter.innerHTML = '<option value="">-- 请选择学生 --</option>';
                
                // 添加学生选项
                students.forEach(student => {
                    const option = document.createElement('option');
                    option.value = student.id;
                    option.textContent = student.name;
                    filter.appendChild(option);
                });
            }
            
            // 渲染积分记录表格
            renderRecordsTable() {
                let records = DataStore.getRecords();
                const studentFilter = this.recordStudentFilter.value;
                const timeFilter = this.recordTimeFilter.value;
                const typeFilter = this.recordTypeFilter.value;
                
                // 应用筛选
                if (studentFilter !== 'all') {
                    records = records.filter(record => record.studentId === parseInt(studentFilter));
                }
                
                if (timeFilter !== 'all') {
                    const now = new Date();
                    let startDate;
                    
                    if (timeFilter === 'today') {
                        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                    } else if (timeFilter === 'week') {
                        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay());
                    } else if (timeFilter === 'month') {
                        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                    }
                    
                    records = records.filter(record => {
                        const recordDate = new Date(record.time);
                        return recordDate >= startDate;
                    });
                }
                
                if (typeFilter !== 'all') {
                    records = records.filter(record => 
                        (typeFilter === 'add' && record.change > 0) || 
                        (typeFilter === 'subtract' && record.change < 0)
                    );
                }
                
                // 按时间倒序排序
                records.sort((a, b) => new Date(b.time) - new Date(a.time));
                
                const tbody = this.recordsTableBody;
                tbody.innerHTML = '';
                
                if (records.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                                <i class="fa-solid fa-history text-3xl mb-2 block"></i>
                                暂无积分记录
                            </td>
                        </tr>
                    `;
                    return;
                }
                
                // 渲染记录表格
                records.forEach(record => {
                    const row = document.createElement('tr');
                    const date = new Date(record.time);
                    const timeString = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
                    
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">${timeString}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${record.studentName}</td>
                        <td class="px-6 py-4 whitespace-nowrap font-medium ${record.change >= 0 ? 'text-green-600' : 'text-red-600'}">${record.change >= 0 ? '+' : ''}${record.change}</td>
                        <td class="px-6 py-4">${record.reason}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${record.operator}</td>
                    `;
                    tbody.appendChild(row);
                });
            }
            
            // 渲染礼品列表
            renderRewardsList() {
                const rewards = DataStore.getRewards();
                const searchTerm = this.rewardSearch.value.toLowerCase();
                
                // 过滤礼品
                const filteredRewards = rewards.filter(reward => 
                    reward.name.toLowerCase().includes(searchTerm) ||
                    (reward.description && reward.description.toLowerCase().includes(searchTerm))
                );
                
                const list = this.rewardsList;
                list.innerHTML = '';
                
                if (filteredRewards.length === 0) {
                    list.innerHTML = `
                        <div class="col-span-full text-center text-gray-500 py-10">
                            <i class="fa-solid fa-gift text-3xl mb-2 block text-gray-300"></i>
                            ${rewards.length === 0 ? '暂无礼品数据，请添加礼品' : '没有找到匹配的礼品'}
                        </div>
                    `;
                    return;
                }
                
                // 渲染礼品列表
                filteredRewards.forEach(reward => {
                    const item = document.createElement('div');
                    item.classList.add('bg-white', 'rounded-lg', 'border', 'border-gray-200', 'p-4', 'hover:shadow-md', 'transition-all');
                    item.innerHTML = `
                        <div class="flex justify-between items-start mb-3">
                            <h3 class="font-bold text-lg">${reward.name}</h3>
                            <span class="font-bold text-accent">${reward.points}积分</span>
                        </div>
                        ${reward.description ? `<p class="text-gray-600 mb-4">${reward.description}</p>` : ''}
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-500">库存: ${reward.stock}</span>
                            <div>
                                <button class="text-primary hover:text-primary/80 mr-2 edit-reward" data-id="${reward.id}">
                                    <i class="fa-solid fa-pen"></i>
                                </button>
                                <button class="text-danger hover:text-danger/80 mr-2 delete-reward" data-id="${reward.id}">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                                <button class="bg-primary hover:bg-primary/90 text-white px-3 py-1 rounded-lg text-sm redeem-reward" data-id="${reward.id}">
                                    兑换
                                </button>
                            </div>
                        </div>
                    `;
                    list.appendChild(item);
                });
                
                // 绑定编辑、删除和兑换按钮事件
                list.querySelectorAll('.edit-reward').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const rewardId = parseInt(e.currentTarget.dataset.id);
                        this.editReward(rewardId);
                    });
                });
                
                list.querySelectorAll('.delete-reward').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const rewardId = parseInt(e.currentTarget.dataset.id);
                        this.deleteReward(rewardId);
                    });
                });
                
                list.querySelectorAll('.redeem-reward').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        const rewardId = parseInt(e.currentTarget.dataset.id);
                        this.showRedeemRewardModal(rewardId);
                    });
                });
            }
            
            // 渲染兑换记录列表
            renderRedemptionsList() {
                let redemptions = DataStore.getRedemptions();
                const studentFilter = this.redemptionStudentFilter.value;
                
                // 应用筛选
                if (studentFilter !== 'all') {
                    redemptions = redemptions.filter(redemption => redemption.studentId === parseInt(studentFilter));
                }
                
                // 按时间倒序排序
                redemptions.sort((a, b) => new Date(b.time) - new Date(a.time));
                
                const list = this.redemptionsList;
                list.innerHTML = '';
                
                if (redemptions.length === 0) {
                    list.innerHTML = `
                        <div class="text-center text-gray-500 py-10">
                            <i class="fa-solid fa-receipt text-3xl mb-2 block text-gray-300"></i>
                            暂无兑换记录
                        </div>
                    `;
                    return;
                }
                
                // 渲染兑换记录列表
                redemptions.forEach(redemption => {
                    const item = document.createElement('div');
                    item.classList.add('bg-gray-50', 'p-3', 'rounded-lg');
                    
                    const date = new Date(redemption.time);
                    const timeString = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
                    
                    item.innerHTML = `
                        <div class="flex justify-between items-start mb-2">
                            <h4 class="font-medium">${redemption.rewardName}</h4>
                            <span class="text-sm text-accent font-bold">-${redemption.points}积分</span>
                        </div>
                        <p class="text-sm text-gray-600 mb-1">学生: ${redemption.studentName}</p>
                        <p class="text-sm text-gray-600 mb-1">时间: ${timeString}</p>
                        ${redemption.note ? `<p class="text-sm text-gray-600">备注: ${redemption.note}</p>` : ''}
                    `;
                    list.appendChild(item);
                });
            }
            
            // 显示添加学生模态框
            showAddStudentModal() {
                this.addStudentModal.classList.remove('hidden');
                this.newStudentName.value = '';
                this.newStudentScore.value = '0';
                this.newStudentName.focus();
            }
            
            // 隐藏添加学生模态框
            hideAddStudentModal() {
                this.addStudentModal.classList.add('hidden');
            }
            
            // 处理添加学生
            handleAddStudent() {
                const name = this.newStudentName.value.trim();
                const score = parseInt(this.newStudentScore.value);
                
                if (!name) {
                    this.showToast('请输入学生姓名', 'error');
                    return;
                }
                
                if (isNaN(score) || score < 0) {
                    this.showToast('请输入有效的积分值', 'error');
                    return;
                }
                
                // 添加学生
                DataStore.addStudent({ name, score });
                
                // 更新界面
                this.renderStudentsTable();
                this.renderScoreStudentsList();
                this.populateStudentFilter();
                this.updateChart();
                
                // 隐藏模态框
                this.hideAddStudentModal();
                
                this.showToast(`成功添加学生: ${name}`, 'success');
            }
            
            // 编辑学生
            editStudent(studentId) {
                const students = DataStore.getStudents();
                const student = students.find(s => s.id === studentId);
                
                if (!student) return;
                
                // 使用模态框编辑学生信息
                this.newStudentName.value = student.name;
                this.newStudentScore.value = student.score;
                this.rewardModalTitle.textContent = '编辑学生';
                this.rewardId.value = studentId;
                
                this.addStudentModal.classList.remove('hidden');
                
                // 修改确认按钮事件
                this.confirmAddStudent.onclick = () => {
                    const name = this.newStudentName.value.trim();
                    const score = parseInt(this.newStudentScore.value);
                    
                    if (!name) {
                        this.showToast('请输入学生姓名', 'error');
                        return;
                    }
                    
                    if (isNaN(score)) {
                        this.showToast('请输入有效的积分值', 'error');
                        return;
                    }
                    
                    // 更新学生信息
                    DataStore.updateStudent({
                        id: studentId,
                        name,
                        score
                    });
                    
                    // 更新界面
                    this.renderStudentsTable();
                    this.renderScoreStudentsList();
                    this.populateStudentFilter();
                    this.updateChart();
                    
                    // 隐藏模态框
                    this.hideAddStudentModal();
                    
                    this.showToast(`成功更新学生: ${name}`, 'success');
                    
                    // 恢复确认按钮的原始功能
                    this.confirmAddStudent.onclick = () => this.handleAddStudent();
                };
            }
            
            // 删除学生
            deleteStudent(studentId) {
                const students = DataStore.getStudents();
                const student = students.find(s => s.id === studentId);
                
                if (!student) return;
                
                if (confirm(`确定要删除学生 "${student.name}" 吗？此操作将同时删除该学生的所有积分和兑换记录！`)) {
                    DataStore.deleteStudents([studentId]);
                    
                    // 更新界面
                    this.renderStudentsTable();
                    this.renderScoreStudentsList();
                    this.populateStudentFilter();
                    this.renderRecordsTable();
                    this.renderRedemptionsList();
                    this.updateChart();
                    
                    this.showToast(`已删除学生: ${student.name}`, 'success');
                }
            }
            
            // 删除选中的学生
            deleteSelectedStudents() {
                const checkboxes = document.querySelectorAll('.student-checkbox:checked');
                const selectedIds = Array.from(checkboxes).map(checkbox => parseInt(checkbox.dataset.id));
                
                if (selectedIds.length === 0) {
                    this.showToast('请先选择要删除的学生', 'warning');
                    return;
                }
                
                const students = DataStore.getStudents();
                const selectedNames = students
                    .filter(s => selectedIds.includes(s.id))
                    .map(s => s.name);
                
                if (confirm(`确定要删除选中的 ${selectedIds.length} 名学生吗？此操作将同时删除这些学生的所有积分和兑换记录！\n\n${selectedNames.join(', ')}`)) {
                    DataStore.deleteStudents(selectedIds);
                    
                    // 更新界面
                    this.renderStudentsTable();
                    this.renderScoreStudentsList();
                    this.populateStudentFilter();
                    this.renderRecordsTable();
                    this.renderRedemptionsList();
                    this.updateChart();
                    
                    // 更新全选复选框状态
                    this.selectAllStudents.checked = false;
                    
                    this.showToast(`已删除 ${selectedIds.length} 名学生`, 'success');
                }
            }
            
            // 更新全选复选框状态
            updateSelectAllCheckbox() {
                const checkboxes = document.querySelectorAll('.student-checkbox');
                const checkedCount = document.querySelectorAll('.student-checkbox:checked').length;
                
                this.selectAllStudents.checked = checkedCount > 0 && checkedCount === checkboxes.length;
                this.selectAllStudents.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;
            }
            
            // 显示多选加分模态框
            showMultiScoreModal() {
                const checkboxes = document.querySelectorAll('.student-checkbox:checked');
                const selectedIds = Array.from(checkboxes).map(checkbox => parseInt(checkbox.dataset.id));
                
                if (selectedIds.length === 0) {
                    this.showToast('请先选择要加分的学生', 'warning');
                    return;
                }
                
                const students = DataStore.getStudents();
                const selectedStudents = students.filter(s => selectedIds.includes(s.id));
                
                // 显示选中的学生列表
                this.selectedStudentsList.innerHTML = '';
                selectedStudents.forEach(student => {
                    const div = document.createElement('div');
                    div.classList.add('text-sm');
                    div.textContent = student.name;
                    this.selectedStudentsList.appendChild(div);
                });
                
                // 重置表单
                this.multiScoreChange.value = '1';
                this.multiScoreReason.value = '';
                
                // 显示模态框
                this.multiScoreModal.classList.remove('hidden');
            }
            
            // 隐藏多选加分模态框
            hideMultiScoreModal() {
                this.multiScoreModal.classList.add('hidden');
            }
            
            // 处理多选加分
            handleMultiScore() {
                const checkboxes = document.querySelectorAll('.student-checkbox:checked');
                const selectedIds = Array.from(checkboxes).map(checkbox => parseInt(checkbox.dataset.id));
                
                if (selectedIds.length === 0) {
                    this.showToast('请先选择要加分的学生', 'warning');
                    return;
                }
                
                const changeValue = parseInt(this.multiScoreChange.value);
                const reason = this.multiScoreReason.value.trim();
                
                if (isNaN(changeValue) || changeValue <= 0) {
                    this.showToast('请输入有效的加分值', 'error');
                    return;
                }
                
                if (!reason) {
                    this.showToast('请输入加分原因', 'error');
                    return;
                }
                
                const students = DataStore.getStudents();
                const selectedStudents = students.filter(s => selectedIds.includes(s.id));
                
                // 为每个选中的学生加分
                selectedStudents.forEach(student => {
                    const newScore = student.score + changeValue;
                    DataStore.updateStudent({
                        id: student.id,
                        score: newScore
                    });
                    
                    // 添加积分记录
                    DataStore.addRecord({
                        studentId: student.id,
                        studentName: student.name,
                        change: changeValue,
                        reason: reason,
                        operator: this.currentUserEl.textContent
                    });
                });
                
                // 更新界面
                this.renderStudentsTable();
                this.renderScoreStudentsList();
                this.renderRankingList('all');
                this.updateChart();
                
                // 隐藏模态框
                this.hideMultiScoreModal();
                
                this.showToast(`已为 ${selectedIds.length} 名学生各加 ${changeValue} 分`, 'success');
            }
            
            // 显示添加礼品模态框
            showAddRewardModal() {
                this.addRewardModal.classList.remove('hidden');
                this.rewardModalTitle.textContent = '添加礼品';
                this.rewardId.value = '';
                this.rewardName.value = '';
                this.rewardPoints.value = '';
                this.rewardDescription.value = '';
                this.rewardStock.value = '1';
                this.rewardName.focus();
            }
            
            // 隐藏添加礼品模态框
            hideAddRewardModal() {
                this.addRewardModal.classList.add('hidden');
            }
            
            // 处理添加/更新礼品
            handleAddReward() {
                const id = this.rewardId.value;
                const name = this.rewardName.value.trim();
                const points = parseInt(this.rewardPoints.value);
                const description = this.rewardDescription.value.trim();
                const stock = parseInt(this.rewardStock.value);
                
                if (!name) {
                    this.showToast('请输入礼品名称', 'error');
                    return;
                }
                
                if (isNaN(points) || points <= 0) {
                    this.showToast('请输入有效的积分值', 'error');
                    return;
                }
                
                if (isNaN(stock) || stock < 0) {
                    this.showToast('请输入有效的库存数量', 'error');
                    return;
                }
                
                if (id) {
                    // 更新现有礼品
                    DataStore.updateReward({
                        id: parseInt(id),
                        name,
                        points,
                        description,
                        stock
                    });
                    
                    this.showToast(`成功更新礼品: ${name}`, 'success');
                } else {
                    // 添加新礼品
                    DataStore.addReward({
                        name,
                        points,
                        description,
                        stock
                    });
                    
                    this.showToast(`成功添加礼品: ${name}`, 'success');
                }
                
                // 更新界面
                this.renderRewardsList();
                
                // 隐藏模态框
                this.hideAddRewardModal();
            }
            
            // 编辑礼品
            editReward(rewardId) {
                const rewards = DataStore.getRewards();
                const reward = rewards.find(r => r.id === rewardId);
                
                if (!reward) return;
                
                // 填充表单
                this.rewardId.value = reward.id;
                this.rewardName.value = reward.name;
                this.rewardPoints.value = reward.points;
                this.rewardDescription.value = reward.description || '';
                this.rewardStock.value = reward.stock;
                this.rewardModalTitle.textContent = '编辑礼品';
                
                // 显示模态框
                this.addRewardModal.classList.remove('hidden');
            }
            
            // 删除礼品
            deleteReward(rewardId) {
                const rewards = DataStore.getRewards();
                const reward = rewards.find(r => r.id === rewardId);
                
                if (!reward) return;
                
                if (confirm(`确定要删除礼品 "${reward.name}" 吗？`)) {
                    DataStore.deleteReward(rewardId);
                    
                    // 更新界面
                    this.renderRewardsList();
                    
                    this.showToast(`已删除礼品: ${reward.name}`, 'success');
                }
            }
            
            // 显示兑换礼品模态框
            showRedeemRewardModal(rewardId) {
                const rewards = DataStore.getRewards();
                const reward = rewards.find(r => r.id === rewardId);
                
                if (!reward) return;
                
                if (reward.stock <= 0) {
                    this.showToast('该礼品库存不足', 'error');
                    return;
                }
                
                // 填充礼品信息
                this.redeemRewardId.value = reward.id;
                this.redeemRewardName.textContent = reward.name;
                this.redeemRewardPoints.textContent = reward.points;
                this.redeemRewardDescription.textContent = reward.description || '';
                
                // 重置学生选择和备注
                this.redeemStudentId.value = '';
                this.studentPointsInfo.classList.add('hidden');
                this.redeemNote.value = '';
                
                // 显示模态框
                this.redeemRewardModal.classList.remove('hidden');
            }
            
            // 隐藏兑换礼品模态框
            hideRedeemRewardModal() {
                this.redeemRewardModal.classList.add('hidden');
            }
            
            // 更新学生积分信息
            updateStudentPointsInfo() {
                const studentId = this.redeemStudentId.value;
                
                if (!studentId) {
                    this.studentPointsInfo.classList.add('hidden');
                    return;
                }
                
                const students = DataStore.getStudents();
                const student = students.find(s => s.id === parseInt(studentId));
                const rewardPoints = parseInt(this.redeemRewardPoints.textContent);
                
                if (!student) return;
                
                // 显示学生积分信息
                this.selectedRedeemStudentName.textContent = student.name;
                this.selectedRedeemStudentPoints.textContent = student.score;
                this.studentPointsInfo.classList.remove('hidden');
                
                // 检查积分是否足够
                if (student.score >= rewardPoints) {
                    this.pointsEnoughMessage.textContent = '积分足够，可以兑换';
                    this.pointsEnoughMessage.className = 'text-sm mt-1 text-green-600';
                } else {
                    this.pointsEnoughMessage.textContent = `积分不足，还需要 ${rewardPoints - student.score} 积分`;
                    this.pointsEnoughMessage.className = 'text-sm mt-1 text-red-600';
                }
                this.pointsEnoughMessage.classList.remove('hidden');
            }
            
            // 处理礼品兑换
            handleRedeemReward() {
                const rewardId = parseInt(this.redeemRewardId.value);
                const studentId = parseInt(this.redeemStudentId.value);
                const note = this.redeemNote.value.trim();
                
                if (!studentId) {
                    this.showToast('请选择要兑换的学生', 'error');
                    return;
                }
                
                const students = DataStore.getStudents();
                const rewards = DataStore.getRewards();
                
                const student = students.find(s => s.id === studentId);
                const reward = rewards.find(r => r.id === rewardId);
                
                if (!student || !reward) {
                    this.showToast('数据错误，请刷新页面重试', 'error');
                    return;
                }
                
                if (student.score < reward.points) {
                    this.showToast('学生积分不足，无法兑换', 'error');
                    return;
                }
                
                if (reward.stock <= 0) {
                    this.showToast('该礼品库存不足', 'error');
                    return;
                }
                
                // 扣除学生积分
                const newScore = student.score - reward.points;
                DataStore.updateStudent({
                    id: studentId,
                    score: newScore
                });
                
                // 减少礼品库存
                DataStore.decreaseRewardStock(rewardId);
                
                // 添加兑换记录
                DataStore.addRedemption({
                    rewardId: rewardId,
                    rewardName: reward.name,
                    studentId: studentId,
                    studentName: student.name,
                    points: reward.points,
                    note: note
                });
                
                // 更新界面
                this.renderRewardsList();
                this.renderRedemptionsList();
                this.renderStudentsTable();
                this.renderScoreStudentsList();
                this.renderRankingList('all');
                this.updateChart();
                
                // 隐藏模态框
                this.hideRedeemRewardModal();
                
                this.showToast(`${student.name} 成功兑换 ${reward.name}`, 'success');
            }
            
            // 显示更改密码模态框
            showChangePasswordModal() {
                this.changePasswordModal.classList.remove('hidden');
                this.currentPasswordInput.value = '';
                this.newPasswordInput.value = '';
                this.confirmPasswordInput.value = '';
                this.passwordError.classList.add('hidden');
                this.currentPasswordInput.focus();
            }
            
            // 隐藏更改密码模态框
            hideChangePasswordModal() {
                this.changePasswordModal.classList.add('hidden');
            }
            
            // 验证密码表单
            validatePasswordForm() {
                const newPassword = this.newPasswordInput.value;
                const confirmPassword = this.confirmPasswordInput.value;
                
                if (newPassword && confirmPassword && newPassword !== confirmPassword) {
                    this.passwordError.classList.remove('hidden');
                    this.passwordErrorMessage.textContent = '新密码与确认密码不一致';
                    return false;
                }
                
                if (newPassword && newPassword.length < 6) {
                    this.passwordError.classList.remove('hidden');
                    this.passwordErrorMessage.textContent = '新密码长度至少为6位';
                    return false;
                }
                
                this.passwordError.classList.add('hidden');
                return true;
            }
            
            // 处理更改密码
            handleChangePassword() {
                const currentPassword = this.currentPasswordInput.value;
                const newPassword = this.newPasswordInput.value;
                const confirmPassword = this.confirmPasswordInput.value;
                
                if (!currentPassword) {
                    this.showToast('请输入当前密码', 'error');
                    return;
                }
                
                if (!newPassword) {
                    this.showToast('请输入新密码', 'error');
                    return;
                }
                
                if (!confirmPassword) {
                    this.showToast('请确认新密码', 'error');
                    return;
                }
                
                if (!this.validatePasswordForm()) {
                    return;
                }
                
                // 验证当前密码
                const users = DataStore.getUsers();
                const currentUser = users[0]; // 假设只有一个用户
                const currentHash = DataStore.hashPassword(currentPassword);
                
                if (currentUser.password !== currentHash) {
                    this.showToast('当前密码不正确', 'error');
                    return;
                }
                
                // 更新密码
                DataStore.updateUserPassword(currentUser.id, newPassword);
                
                // 隐藏模态框
                this.hideChangePasswordModal();
                
                this.showToast('密码已成功更新', 'success');
            }
            
            // 处理退出登录
            handleLogout() {
                if (confirm('确定要退出登录吗？')) {
                    this.appPage.classList.add('hidden');
                    this.loginPage.classList.remove('hidden');
                    
                    // 重置登录表单
                    this.usernameInput.value = '';
                    this.passwordInput.value = '';
                    const loginBtn = document.querySelector('.btn-login');
                    loginBtn.innerHTML = '<i class="fa-solid fa-sign-in mr-2"></i>登录';
                    loginBtn.disabled = false;
                    loginBtn.style.background = 'linear-gradient(135deg, #3B82F6 0%, #2563EB 100%)';
                    
                    this.showToast('已成功退出登录', 'success');
                }
            }
            
            // 处理文件导入
            handleFileImport(event) {
                const file = event.target.files[0];
                if (!file) return;
                
                const reader = new FileReader();
                reader.onload = (e) => {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, { type: 'array' });
                        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                        const jsonData = XLSX.utils.sheet_to_json(firstSheet);
                        
                        if (jsonData.length === 0) {
                            this.showToast('导入的文件中没有数据', 'error');
                            return;
                        }
                        
                        // 处理导入的数据
                        const importedStudents = [];
                        let successCount = 0;
                        let errorCount = 0;
                        
                        jsonData.forEach((row, index) => {
                            const name = row['姓名'] || row['name'] || row['学生姓名'];
                            let score = row['积分'] || row['score'] || row['当前积分'] || 0;
                            
                            if (name) {
                                // 确保score是数字
                                if (typeof score === 'string') {
                                    score = parseInt(score) || 0;
                                }
                                
                                importedStudents.push({ name, score });
                                successCount++;
                            } else {
                                errorCount++;
                            }
                        });
                        
                        if (importedStudents.length === 0) {
                            this.showToast('导入的文件中没有有效的学生数据', 'error');
                            return;
                        }
                        
                        // 添加导入的学生
                        importedStudents.forEach(student => {
                            DataStore.addStudent(student);
                        });
                        
                        // 更新界面
                        this.renderStudentsTable();
                        this.renderScoreStudentsList();
                        this.populateStudentFilter();
                        this.updateChart();
                        
                        // 显示导入结果
                        let message = `成功导入 ${successCount} 名学生`;
                        if (errorCount > 0) {
                            message += `，${errorCount} 条记录格式错误`;
                        }
                        
                        this.showToast(message, 'success');
                    } catch (error) {
                        console.error('导入失败:', error);
                        this.showToast('文件导入失败，请检查文件格式', 'error');
                    }
                };
                
                reader.readAsArrayBuffer(file);
                
                // 重置文件输入，允许再次选择同一文件
                event.target.value = '';
            }
            
            // 导出学生数据
            exportStudents() {
                const students = DataStore.getStudents();
                if (students.length === 0) {
                    this.showToast('没有学生数据可导出', 'warning');
                    return;
                }
                
                // 准备导出数据
                const data = students.map(student => ({
                    '学号': student.id,
                    '姓名': student.name,
                    '积分': student.score
                }));
                
                // 创建工作簿和工作表
                const worksheet = XLSX.utils.json_to_sheet(data);
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, '学生列表');
                
                // 导出文件
                XLSX.writeFile(workbook, '学生列表.xlsx');
                
                this.showToast('学生数据导出成功', 'success');
            }
            
            // 导出排行榜
            exportRanking(filter) {
                let students = DataStore.getStudents();
                
                // 按积分排序
                students.sort((a, b) => b.score - a.score);
                
                // 应用筛选
                if (filter === 'top10') {
                    students = students.slice(0, 10);
                } else if (filter === 'bottom10') {
                    students = students.slice(-10).reverse();
                }
                
                if (students.length === 0) {
                    this.showToast('没有排名数据可导出', 'warning');
                    return;
                }
                
                // 准备导出数据
                const data = students.map((student, index) => ({
                    '排名': index + 1,
                    '姓名': student.name,
                    '积分': student.score
                }));
                
                // 创建工作簿和工作表
                const worksheet = XLSX.utils.json_to_sheet(data);
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, '积分排行榜');
                
                // 导出文件
                let fileName = '积分排行榜';
                if (filter === 'top10') fileName = '前十名排行榜';
                if (filter === 'bottom10') fileName = '后十名排行榜';
                
                XLSX.writeFile(workbook, `${fileName}.xlsx`);
                
                this.showToast('排行榜导出成功', 'success');
            }
            
            // 导出积分记录
            exportRecords() {
                let records = DataStore.getRecords();
                
                if (records.length === 0) {
                    this.showToast('没有积分记录可导出', 'warning');
                    return;
                }
                
                // 准备导出数据
                const data = records.map(record => {
                    const date = new Date(record.time);
                    return {
                        '时间': date.toLocaleString(),
                        '学生': record.studentName,
                        '积分变动': record.change,
                        '原因': record.reason,
                        '操作人': record.operator
                    };
                });
                
                // 创建工作簿和工作表
                const worksheet = XLSX.utils.json_to_sheet(data);
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, '积分记录');
                
                // 导出文件
                XLSX.writeFile(workbook, '积分记录.xlsx');
                
                this.showToast('积分记录导出成功', 'success');
            }
            
            // 导出兑换记录
            exportRedemptions() {
                let redemptions = DataStore.getRedemptions();
                
                if (redemptions.length === 0) {
                    this.showToast('没有兑换记录可导出', 'warning');
                    return;
                }
                
                // 准备导出数据
                const data = redemptions.map(redemption => {
                    const date = new Date(redemption.time);
                    return {
                        '时间': date.toLocaleString(),
                        '学生': redemption.studentName,
                        '礼品': redemption.rewardName,
                        '消耗积分': redemption.points,
                        '备注': redemption.note || ''
                    };
                });
                
                // 创建工作簿和工作表
                const worksheet = XLSX.utils.json_to_sheet(data);
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, '兑换记录');
                
                // 导出文件
                XLSX.writeFile(workbook, '兑换记录.xlsx');
                
                this.showToast('兑换记录导出成功', 'success');
            }
            
            // 打印学生列表
            printStudents() {
                window.print();
            }
            
            // 打印排行榜
            printRanking() {
                window.print();
            }
            
            // 打印积分记录
            printRecords() {
                window.print();
            }
            
            // 打印兑换记录
            printRedemptions() {
                window.print();
            }
        }

        // 初始化应用
        function initApp() {
            window.app = new ScoreManagementApp();
        }
    </script>
</body>
</html>